package org.example.school.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.common.Result;
import org.example.school.entity.Assignments;
import org.example.school.entity.AssignmentSubmissions;
import org.example.school.entity.Students;
import org.example.school.entity.TeacherClassRelations;
import org.example.school.entity.Teachers;
import org.example.school.model.dto.AssignmentsDTO;
import org.example.school.model.dto.TeacherAssignmentSubmissionDTO;
import org.example.school.service.IAssignmentSubmissionsService;
import org.example.school.service.IAssignmentsService;
import org.example.school.service.IStudentsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class HomeWorkInfo extends CommonInfo{
    
    @Autowired
    private IAssignmentsService assignmentsService;
    
    @Autowired
    private IAssignmentSubmissionsService assignmentSubmissionsService;
    
    @Autowired
    private IStudentsService studentsService;

    /**
     * 教师发布作业
     * @param assignmentsDTO 作业信息
     * @return 发布结果
     */
    public Result<String> assignHomework(AssignmentsDTO assignmentsDTO) {
        try {
            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            
            Assignments assignments = new Assignments();
            BeanUtils.copyProperties(assignmentsDTO, assignments);
            
            // 设置创建时间和教师ID
            assignments.setCreatedAt(LocalDateTime.now());
            assignments.setTeacherId(teacher.getId());
            assignments.setDueDate(assignmentsDTO.getDueDate());
            assignments.setIsDue(false);
            
            // 保存作业信息
            boolean saved = assignmentsService.save(assignments);
            if (saved) {
                return Result.success("作业发布成功");
            } else {
                return Result.error("作业发布失败");
            }
        } catch (Exception e) {
            return Result.error("作业发布异常: " + e.getMessage());
        }
    }

    /**
     * 根据班级ID查询作业列表
     * @param classId 班级ID
     * @return 作业列表
     */
    public Result<List<Assignments>> getHomeworkListByClassId(Integer classId) {
        try {
            // 验证教师是否有权限查看该班级的作业
            Result<List<TeacherClassRelations>> classRelationsResult = this.getClassInfo();
            if (!classRelationsResult.isSuccess()) {
                return Result.error("获取教师班级关系失败");
            }
            
            List<TeacherClassRelations> relations = classRelationsResult.getData();
            boolean hasPermission = relations.stream()
                    .anyMatch(relation -> relation.getClassId().equals(classId));
                    
            if (!hasPermission) {
                return Result.error("无权限查看该班级作业");
            }
            
            // 查询作业列表
            QueryWrapper<Assignments> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            queryWrapper.orderByDesc("created_at");
            
            List<Assignments> assignmentsList = assignmentsService.list(queryWrapper);
            return Result.success(assignmentsList);
        } catch (Exception e) {
            return Result.error("查询作业列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前教师所有班级的作业列表
     * @return 作业列表
     */
    public Result<List<Assignments>> getAllHomeworkList() {
        try {
            // 获取教师负责的所有班级
            Result<List<TeacherClassRelations>> classRelationsResult = this.getClassInfo();
            if (!classRelationsResult.isSuccess()) {
                return Result.error("获取教师班级关系失败");
            }
            
            List<TeacherClassRelations> relations = classRelationsResult.getData();
            List<Integer> classIds = relations.stream()
                    .map(TeacherClassRelations::getClassId)
                    .collect(Collectors.toList());
            
            if (classIds.isEmpty()) {
                return Result.success(null);
            }
            
            // 查询所有班级的作业
            QueryWrapper<Assignments> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("class_id", classIds);
            queryWrapper.orderByDesc("created_at");
            
            List<Assignments> assignmentsList = assignmentsService.list(queryWrapper);
            return Result.success(assignmentsList);
        } catch (Exception e) {
            return Result.error("查询作业列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取作业的提交情况
     * @param assignmentId 作业ID
     * @return 作业提交列表
     */
    public Result<List<TeacherAssignmentSubmissionDTO>> getAssignmentSubmissions(Long assignmentId) {
        try {
            // 检查作业是否存在
            Assignments assignment = assignmentsService.getById(assignmentId);
            if (assignment == null) {
                return Result.error("作业不存在");
            }
            
            // 检查教师是否有权限查看该作业
            Teachers teacher = this.getUserByTeacher().getData();
            if (!assignment.getTeacherId().equals(teacher.getId())) {
                return Result.error("无权限查看该作业提交情况");
            }
            
            // 查询该作业的所有提交记录
            QueryWrapper<AssignmentSubmissions> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("assignment_id", assignmentId);
            queryWrapper.orderByDesc("submitted_at");
            
            List<AssignmentSubmissions> submissions = assignmentSubmissionsService.list(queryWrapper);
            
            // 转换为TeacherAssignmentSubmissionDTO
            List<TeacherAssignmentSubmissionDTO> submissionDTOs = submissions.stream().map(submission -> {
                TeacherAssignmentSubmissionDTO dto = new TeacherAssignmentSubmissionDTO();
                BeanUtils.copyProperties(submission, dto);
                
                // 获取学生信息
                Students student = studentsService.getById(submission.getStudentId());
                if (student != null) {
                    dto.setStudentName(student.getFullName());
                    dto.setStudentNumber(student.getStudentNumber());
                }
                
                return dto;
            }).collect(Collectors.toList());
            
            return Result.success(submissionDTOs);
        } catch (Exception e) {
            return Result.error("查询作业提交情况异常: " + e.getMessage());
        }
    }
    
    /**
     * 评分作业
     * @param submissionId 提交记录ID
     * @param grade 分数
     * @param feedback 评语
     * @return 评分结果
     */
    public Result<String> gradeAssignmentSubmission(Long submissionId, String grade, String feedback) {
        try {
            // 检查提交记录是否存在
            AssignmentSubmissions submission = assignmentSubmissionsService.getById(submissionId);
            if (submission == null) {
                return Result.error("作业提交记录不存在");
            }
            
            // 检查教师是否有权限评分
            Assignments assignment = assignmentsService.getById(submission.getAssignmentId());
            Teachers teacher = this.getUserByTeacher().getData();
            if (!assignment.getTeacherId().equals(teacher.getId())) {
                return Result.error("无权限评分该作业");
            }
            
            // 更新评分信息
            submission.setGrade(grade);
            submission.setFeedback(feedback);
            // 状态设置为3(已批改)
            submission.setStatus(3);
            
            boolean updated = assignmentSubmissionsService.updateById(submission);
            if (updated) {
                return Result.success("作业评分成功");
            } else {
                return Result.error("作业评分失败");
            }
        } catch (Exception e) {
            return Result.error("作业评分异常: " + e.getMessage());
        }
    }
    
    /**
     * 退回作业
     * @param submissionId 提交记录ID
     * @param feedback 退回原因
     * @return 退回结果
     */
    public Result<String> rejectAssignmentSubmission(Long submissionId, String feedback) {
        try {
            // 检查提交记录是否存在
            AssignmentSubmissions submission = assignmentSubmissionsService.getById(submissionId);
            if (submission == null) {
                return Result.error("作业提交记录不存在");
            }
            
            // 检查教师是否有权限操作
            Assignments assignment = assignmentsService.getById(submission.getAssignmentId());
            Teachers teacher = this.getUserByTeacher().getData();
            if (!assignment.getTeacherId().equals(teacher.getId())) {
                return Result.error("无权限操作该作业");
            }
            
            // 更新信息
            submission.setFeedback(feedback);
            // 状态设置为4(已退回)
            submission.setStatus(4);
            
            boolean updated = assignmentSubmissionsService.updateById(submission);
            if (updated) {
                return Result.success("作业退回成功");
            } else {
                return Result.error("作业退回失败");
            }
        } catch (Exception e) {
            return Result.error("作业退回异常: " + e.getMessage());
        }
    }

    public void autoGenerateSelectIsDue() {
        List<Assignments> assignments = assignmentsService.lambdaQuery().eq(Assignments::getIsDue, false).list();
        assignments.forEach(assignment -> {
            if (assignment.getDueDate().isAfter(LocalDateTime.now())) {
                assignment.setIsDue(true);
                assignmentsService.updateById(assignment);
            }
        });
    }
}